#include "../server.hpp"

class EchoServer{
private:
    void OnConnected(const PtrConnection &conn){
        LOG_DEBUG("NEW CONNECTION: %p", conn.get());
    }
    void OnClosed(const PtrConnection &conn){
        LOG_DEBUG("CLOSED CONNECTION: %p", conn.get());
    }
    void OnMessage(const PtrConnection &conn, Buffer *buf){
    // 注册写完成回调，确保数据发送后再关闭连接;
        conn->Send(buf->GetReadPos(), buf->ReadableSize());
        buf->MoveReadOffset(buf->ReadableSize());
        conn->Shutdown();
        // conn->ShutdownWrite();
    }

public:
    EchoServer(int port): _server(port) {
        _server.SetThreadCount(2);
        _server.EnableInactiveRelease(10);
        _server.SetClosedCallback(std::bind(&EchoServer::OnClosed, this, std::placeholders::_1));
        _server.SetConnectedCallback(std::bind(&EchoServer::OnConnected, this, std::placeholders::_1));
        _server.SetMessageCallback(std::bind(&EchoServer::OnMessage, this, std::placeholders::_1, std::placeholders::_2));
    }

    void Start(){
        _server.Start();
    }
    
private:
    TcpServer _server;
};